package com.apes.enquiry.product.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.brand.model.SpBrand;
import com.apes.enquiry.brand.repository.SpBrandRepository;
import com.apes.enquiry.enquiry.model.Enquiry;
import com.apes.enquiry.enquiry.model.QuoteResult;
import com.apes.enquiry.enquiry.repository.EnquiryRepository;
import com.apes.enquiry.enquiry.repository.QuoteResultRepository;
import com.apes.enquiry.product.model.*;
import com.apes.enquiry.product.repository.*;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.logger.ApesLoggerService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxEvent;
import com.apes.framework.plugin.outbox.OutboxEventRepository;
import com.apes.framework.plugin.outbox.OutboxEventService;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @ClassName SpProductService
 * @Description 描述 供应商平台商品服务类
 * @Author wushilong
 * @Date 2022/10/14 11:13
 * @Version 1.0
 */

@Service
public class SpProductService extends DomainService {

    @Autowired
    private SpBrandRepository spBrandRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SpProductRepository spProductRepository;

    @Autowired
    private OilyProductRepository oilyProductRepository;

    @Autowired
    private AccumulatorProductRepository accumulatorProductRepository;

    @Autowired
    private TyreProductRepository tyreExtendRepository;

    @Autowired
    private AutomobileBrandRepository automobileBrandRepository;

    @Autowired
    private BrandUploadingRepository brandUploadingRepository;

    @Autowired
    private PartyRoleRepository partyRoleRepository;

    @Autowired
    private SpCategoryRepository categoryRepository;

    @Autowired
    private EnquiryRepository enquiryRepository;

    @Autowired
    private QuoteResultRepository quoteResultRepository;

    /**
     * 动态条件查询
     *
     * @param request
     * @return
     */
    public Map conditionQuery(SimpleRequest request) {
        JSONObject jo = request.getJO();
        String productState = jo.getString("productState");
        if ("审核中".equals(productState)) productState = "review";
        if ("无法系统报价".equals(productState)) productState = "notOffer";
        if ("待维护品牌件关系".equals(productState)) productState = "awaitMaintain";
        if ("可系统报价".equals(productState)) productState = "offer";
        if ("待上架".equals(productState)) productState = "awaitPutaway";
        if ("临时商品".equals(productState)) productState = "history";
        if(request.getSession()==null){
            throw new RuntimeException("获取对象失败,请刷新页面！");
        }
        User user = userRepository.findOne(Integer.valueOf(request.getSession().getUserId()));
        PartyRole supplier = partyRoleRepository.findOne(user.getPerson().getId());
        if ("yyadmin".equals(user.getPerson().getId())) {
            supplier = null;
        }

        int page = jo.getInteger("page") < 0 ? 0 : jo.getInteger("page");

        Page<SpProduct> spProductPage = spProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("merchantProduct", "EQ", jo.getString("merchantProduct"),
                "OE", "EQ", jo.getString("pn"),
                "spBrand", "EQ", jo.getObject("brand", SpBrand.class),
                "category", "EQ", jo.getObject("category", Category.class),
                "productState", "EQ", productState,
                "name", "EQ", jo.getString("name"),
                "type", "EQ", jo.getString("type"),
                "supplier", "EQ", supplier
        ), PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));

        return MapUtil.mapper("content", spProductPage.getContent(), "page", page, "sum", spProductPage.getTotalPages());

    }


    /**
     * 编辑之前查询该条数据
     *
     * @param request
     * @return
     */
    public Map findById(SimpleRequest request) {
        String id = request.getJO().getString("id");
        if ("".equals(id) || id == null) {
            return null;
        }
        Map map = new HashMap();
        SpProduct spProduct = spProductRepository.findOne(id);
        map.put("spProduct", spProduct);
        map.put("innerBusinessKey", spProduct.getInnerBusinessKey());
        map.put("innerBusinessType", spProduct.getInnerBusinessType());
        return map;
    }

    /**
     * 编辑之前查询该条数据扩展数据
     *
     * @param request
     * @return
     */
    public Map findBySpId(SimpleRequest request) {
        String spId = request.getJO().getString("spId");
        String type = request.getJO().getString("type");
        if ("".equals(spId) || spId == null) {
            return null;
        }
        Map map = new HashMap();
        if ("轮胎".equals(type)) {
            map.put("tyre", tyreExtendRepository.findBySpId(spId));
        }
        if ("机油".equals(type)) {
            map.put("oily", oilyProductRepository.findBySpId(spId));
        }
        if ("蓄电池".equals(type)) {
            map.put("accumulator", accumulatorProductRepository.findBySpId(spId));
        }
        return map;
    }


    /**
     * 新增修改商品列表
     *
     * @param request
     * @return
     */
    public Map updateSpProduct(SimpleRequest request) {
        SpProduct newSpProduct = request.getJO().getObject("spProduct", SpProduct.class);
        if(newSpProduct.getNotTaxUnitPrice()<0 || newSpProduct.getMerchantStockQty()<0){
            throw new RuntimeException("价格库存不能小于0！") ;
        }
        newSpProduct.setNotTaxUnitPrice(Double.parseDouble(String.format("%.2f", newSpProduct.getNotTaxUnitPrice())));
        SpBrand spBrand = request.getJO().getObject("spBrand", SpBrand.class);
        newSpProduct.setSpBrand(spBrand);
        User user = userRepository.findOne(Integer.valueOf(request.getSession().getUserId()));
        String guaranteePeriod = request.getJO().getString("guaranteePeriod");
        if(guaranteePeriod==null || guaranteePeriod.equals("")){
            guaranteePeriod="0";
        }
        if (StringUtils.isEmpty(newSpProduct.getId())) {
            PartyRole partyRole = partyRoleRepository.findOne(user.getPerson().getId());
            //新增商品
            newSpProduct.setType(request.getJO().getString("type"));
            newSpProduct.setGuaranteePeriod(guaranteePeriod);
            newSpProduct.setProductState("review");
            newSpProduct.setMateState("underway");
            String original = newSpProduct.getSpBrand().getQualityName();
            if ("原厂件".equals(original) || "原厂(4S店)件".equals(original) || "非原厂(4S店)件".equals(original)) {
                newSpProduct.setStandardType("Whole");
            } else if(request.getJO().getString("type").equals("轮胎")) {
                newSpProduct.setStandardType("Tyre");
            } else if(request.getJO().getString("type").equals("机油")) {
                newSpProduct.setStandardType("Oily");
            } else if(request.getJO().getString("type").equals("蓄电池")) {
                newSpProduct.setStandardType("Accumulator");
            }else{
                newSpProduct.setStandardType("brandWhole");
            }
            newSpProduct.setSupplier(partyRole);
            newSpProduct.setPutawayState(false);
        } else {
            //修改商品
            SpProduct spProductNew = spProductRepository.findOne(newSpProduct.getId());
            //判断类型是否更改，删除子记录
            if (!spProductNew.getType().equals(request.getJO().getString("type"))) {
                delExpand(spProductNew.getType(), spProductNew.getId());
            }
            newSpProduct.setType(request.getJO().getString("type"));
            newSpProduct.setGuaranteePeriod(guaranteePeriod);
            //如果修改价格则记录日志
            if (!newSpProduct.getNotTaxUnitPrice().equals(spProductNew.getNotTaxUnitPrice())) {
                String remark = "不含税单价：" + spProductNew.getNotTaxUnitPrice() + "-->" + newSpProduct.getNotTaxUnitPrice();
                Log(user, newSpProduct, "修改价格", remark);
            }
            //如果修改库存则记录日志
            if (!newSpProduct.getMerchantStockQty().equals(spProductNew.getMerchantStockQty())) {
                String remark = "商品库存：" + spProductNew.getMerchantStockQty() + "-->" + newSpProduct.getMerchantStockQty();
                Log(user, newSpProduct, "修改库存", remark);
            }

        }
        Map map = new HashMap();
        SpProduct spProduct = null;
        if (StringUtils.isEmpty(newSpProduct.getId())) {
            newSpProduct.setWrite(false);
            spProduct = spProductRepository.saveAndFlush(newSpProduct);
            //事务发件箱
            transactionOutbox(spProduct, user);
            //记录日志
            Log(user, newSpProduct, "创建", null);
        } else {
            spProduct = spProductRepository.saveAndFlush(newSpProduct);
            //事务发件箱
            transactionOutbox(spProduct, user);
        }

        map.put("spProduct", spProduct);
        map.put("innerBusinessKey", spProduct.getInnerBusinessKey());
        map.put("innerBusinessType", spProduct.getInnerBusinessType());
        map.put("type", spProduct.getType());
        //判断商品扩展信息
        if ("轮胎".equals(spProduct.getType())) {
            TyreProduct newTyreProduct = JSON.parseObject(request.getJO().getString("tyre"), TyreProduct.class);
            if (newTyreProduct != null) {
                newTyreProduct.setSpProduct(spProduct);
                newTyreProduct = tyreExtendRepository.saveAndFlush(newTyreProduct);
            }
            map.put("tyre", newTyreProduct);
        }
        if ("蓄电池".equals(spProduct.getType())) {
            AccumulatorProduct newAccumulatorProduct = JSON.parseObject(request.getJO().getString("accumulator"), AccumulatorProduct.class);
            if (newAccumulatorProduct != null) {
                newAccumulatorProduct.setSpProduct(spProduct);
                newAccumulatorProduct = accumulatorProductRepository.saveAndFlush(newAccumulatorProduct);
            }
            map.put("accumulator", newAccumulatorProduct);
        }
        if ("机油".equals(spProduct.getType())) {
            OilyProduct newOily = JSON.parseObject(request.getJO().getString("oily"), OilyProduct.class);
            if (newOily != null) {
                newOily.setSpProduct(spProduct);
                newOily = oilyProductRepository.saveAndFlush(newOily);
            }
            map.put("oily", newOily);

        }
        return map;
    }

    /**
     * 事务发件箱
     *
     * @param spProduct
     * @param user
     */
    public void transactionOutbox(SpProduct spProduct, User user) {
        List spProducts = new ArrayList();
        spProducts.add(spProduct);
        //规则匹配
        OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
        switch (spProduct.getType()) {
            case "全车件":
                wrapper.setSubscriber("sp.spProduct.standardContrast");
                break;
            case "轮胎":
                wrapper.setSubscriber("sp.tyreProduct.standardContrast");
                break;
            case "机油":
                wrapper.setSubscriber("sp.oilyProduct.standardContrast");
                break;
            case "蓄电池":
                wrapper.setSubscriber("sp.accumulatorProduct.standardContrast");
                break;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yy-mm-dd HH:mm:ss");
        String random = String.valueOf(Math.random()).substring(0, 3);
        wrapper.setAggregateId(user.getOrigin() + sdf.format(new Date()) + random);//聚合根ID（非必项）tp:方便追溯发生异常的服务,最好是业务单据单号
        wrapper.setPayload(JSON.toJSONString(spProducts));
        SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);

    }


    /**
     * 修改价格库存列表
     *
     * @param request
     * @return
     */
    public Map updateSpProductPrice(SimpleRequest request) {
        SpProduct spProduct = spProductRepository.findOne(request.getJO().getString("id"));
        Double notTaxUnitPrice = request.getJO().getDouble("notTaxUnitPrice");
        Integer merchantStockQty = request.getJO().getInteger("merchantStockQty");
        if (!notTaxUnitPrice.equals(spProduct.getNotTaxUnitPrice())) {
            String remark = "不含税单价：" + spProduct.getNotTaxUnitPrice() + "-->" + notTaxUnitPrice;
            User user = request.getJO().getObject("user", User.class);
            Log(user, spProduct, "修改价格", remark);
        }
        if (!merchantStockQty.equals(spProduct.getMerchantStockQty())) {
            String remark = "商品库存：" + spProduct.getMerchantStockQty() + "-->" + merchantStockQty;
            User user = request.getJO().getObject("user", User.class);
            Log(user, spProduct, "修改库存", remark);
        }
        spProduct.setNotTaxUnitPrice(Double.parseDouble(String.format("%.2f", notTaxUnitPrice)));
        spProduct.setMerchantStockQty(merchantStockQty);
        spProductRepository.saveAndFlush(spProduct);
        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }


    /**
     * 批量更新上下架
     *
     * @param request
     * @return
     */
    public Map edit(SimpleRequest request) {
        List<SpProduct> spProductList = request.getA("spProductList", SpProduct.class);
        //保存并返回
        boolean edit = request.getJO().getBoolean("edit");
        String whether = "下架";
        if (edit) {
            whether = "上架";
        }
        User user = request.getJO().getObject("user", User.class);
        for (SpProduct spProduct : spProductList) {
            //事务发件箱
            //transactionOutbox(spProduct, user);
            //记录日志
            Log(user, spProduct, whether, null);
            spProduct.setWrite(false);
            spProduct.setPutawayState(edit);
            if(spProduct.getMateState().equals("succeed") && spProduct.isPutawayState()){
                spProduct.setProductState("offer");
            }
            if(spProduct.getMateState().equals("succeed") && !spProduct.isPutawayState()){
                spProduct.setProductState("awaitPutaway");
            }
            spProductRepository.saveAndFlush(spProduct);
        }

        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }


    /**
     * 商品列表更新单个上下架
     *
     * @param request
     * @return
     */
    public Map editById(SimpleRequest request) {
        SpProduct spProduct = spProductRepository.findOne(request.getJO().getString("id"));
        Boolean putawayState = request.getJO().getBoolean("edit");
        spProduct.setPutawayState(putawayState);
        String whether = "下架";
        if (putawayState) {
            whether = "上架";
        }

        User user = request.getJO().getObject("user", User.class);
        Log(user, spProduct, whether, null);
        spProduct.setWrite(false);

        if(spProduct.getMateState().equals("succeed") && spProduct.isPutawayState()){
            spProduct.setProductState("offer");
        }
        if(spProduct.getMateState().equals("succeed") && !spProduct.isPutawayState()){
            spProduct.setProductState("awaitPutaway");
        }
        spProduct = spProductRepository.saveAndFlush(spProduct);

        //事务发件箱
        //transactionOutbox(spProduct, user);
        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }

    /**
     * 商品详情更新单个上下架
     *
     * @param request
     * @return
     */
    public SpProduct speditById(SimpleRequest request) {
        SpProduct spProduct = spProductRepository.findOne(request.getJO().getString("id"));
        Boolean putawayState = request.getJO().getBoolean("edit");
        spProduct.setPutawayState(putawayState);
        String whether = "下架";
        if (putawayState) {
            whether = "上架";
        }
        User user = request.getJO().getObject("user", User.class);
        Log(user, spProduct, whether, null);
        spProduct.setWrite(false);
        if(spProduct.getMateState().equals("succeed") && spProduct.isPutawayState()){
            spProduct.setProductState("offer");
        }
        if(spProduct.getMateState().equals("succeed") && !spProduct.isPutawayState()){
            spProduct.setProductState("awaitPutaway");
        }
        spProduct = spProductRepository.saveAndFlush(spProduct);
        //事务发件箱
        //transactionOutbox(spProduct, user);
        return spProduct;
    }

    /**
     * 记录操作日志
     *
     * @param user
     * @param spProduct
     * @param operate
     * @param remark
     */
    private void Log(User user, SpProduct spProduct, String operate, String remark) {
        SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                "businessType", spProduct.getInnerBusinessType(),
                "businessKey", spProduct.getInnerBusinessKey(),
                "operate", operate,
                "remark", remark,
                "workPostName", user.getPosts().get(0).getName(),
                "audit", spProduct.getAudit(),
                "operator_id", user.getId()));
    }

    /**
     * 批量删除
     *
     * @param request
     * @return
     */
    public Map delDatchSpProduct(SimpleRequest request) {
        List<SpProduct> delSpProduct = request.getA("del", SpProduct.class);

        for (SpProduct spProduct : delSpProduct) {
            if (Objects.nonNull(spProduct.getId())) {
                delExpand(spProduct.getType(), spProduct.getId());
                try{
                    spProductRepository.delete(spProduct);
                }catch (RuntimeException e){
                    throw new RuntimeException("部分商品已被使用,不可删除！");
                }
            }
        }
        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }

    /**
     * 商品列表删除单条数据
     *
     * @param request
     * @return
     */
    public Map delById(SimpleRequest request) {
        SpProduct spProduct = request.getJO().getObject("del", SpProduct.class);
        String type = spProduct.getType();
        delExpand(type, spProduct.getId());
        try{
            spProductRepository.delete(spProduct);
        }catch (RuntimeException e){
            throw new RuntimeException("商品已被使用,不可删除！");
        }

        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }

    /**
     * 商品详情删除单条数据
     *
     * @param request
     * @return
     */
    public String spdelById(SimpleRequest request) {
        SpProduct spProduct = request.getJO().getObject("del", SpProduct.class);
        String type = spProduct.getType();
        delExpand(type, spProduct.getId());
        try{
            spProductRepository.delete(spProduct);
        }catch (RuntimeException e){
            throw new RuntimeException("商品已被使用,不可删除！");
        }
        return "删除成功!";
    }

    /**
     * 删除子记录
     *
     * @param type
     * @param id
     */
    public void delExpand(String type, String id) {
        if ("轮胎".equals(type)) {
            TyreProduct tyreProduct = tyreExtendRepository.findBySpId(id);
            if (tyreProduct == null) return;
            tyreExtendRepository.delete(tyreProduct);
        }
        if ("蓄电池".equals(type)) {
            AccumulatorProduct accumulatorProduct = accumulatorProductRepository.findBySpId(id);
            if (accumulatorProduct == null) return;
            accumulatorProductRepository.delete(accumulatorProduct);
        }

        if ("机油".equals(type)) {
            OilyProduct oilyProduct = oilyProductRepository.findBySpId(id);
            if (oilyProduct == null) return;
            oilyProductRepository.delete(oilyProduct);
        }

    }


    /**
     * 根据编号删除商品列表
     *
     * @param request
     * @return
     */
    public String delSpProduct(SimpleRequest request) {
        spProductRepository.delete(request.getJO().getString("id"));
        return "删除成功";
    }

    /**
     * 上传全车件类商品入口
     *
     * @param request
     */
    public void uploadingSpProduct(SimpleRequest request) {
        //Excel信息
        JSONObject importData = request.get("importData");
        User user = userRepository.findOne(Integer.parseInt(request.getSession().getUserId()));

        //准入校验与数据补全
        List spProducts = appendImportReturn_New(importData, user);
        if (spProducts.size() <= 0) return;
        double num = Math.ceil(spProducts.size()/1000.0);
        int index = 0;
        for (int i = 0; i <num ; i++) {
            List list = spProducts.subList(index, Math.min(index + 1000, spProducts.size()));
            SimpleDateFormat sdf = new SimpleDateFormat("yy-mm-dd HH:mm:ss");
            //通过事务发件箱实现标准对照/状态字段回写
            OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
            wrapper.setSubscriber("sp.spProduct.standardContrast");
            String random = String.valueOf(Math.random()).substring(0, 3);
            //聚合根ID（非必项）tp:方便追溯发生异常的服务,(当前用户账号加时间戳)
            wrapper.setAggregateId(user.getOrigin() + sdf.format(new Date()) + random);
            wrapper.setPayload(JSON.toJSONString(list));
            SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);
            index+=1000;
            if(index>=spProducts.size()){
                return;
            }

        }

    }

    /**
     * 准入校验与数据补全
     *
     * @param importData
     * @param user
     * @return
     */
    private List appendImportReturn_New(JSONObject importData, User user) {
        List spProducts = Collections.synchronizedList(new ArrayList());
        List notProducts = Collections.synchronizedList(new ArrayList());
        //（零件号+品牌）列表
        Set<String> PNAndBrand = spProductRepository.findPNAndBrandAll();
        //品牌列表
        List<String> allName = spBrandRepository.findAllName();
        //标准名称列表
        List<String> categories = categoryRepository.findByNameAll();
        //汽车品牌列表
        List<String> autoBrand = automobileBrandRepository.findAllName();
        //品牌+品质组成map
        List<Map<String, String>> allQuality = spBrandRepository.findAllQuality();
        Map<String, String> quality = allQuality.stream().filter(Objects::nonNull).collect(Collectors.toMap(item -> item.get("name"), item -> item.get("qualityName")));
        //开始校验数据
        importData.forEach((k, v) -> {
            JSONArray importArray = (JSONArray) v;
            if (((JSONArray) importArray.get(0)).size() != 12) throw new RuntimeException("导入模板错误，请检查文件并重新上传！");
            AtomicInteger i = new AtomicInteger(1);
            double size = importArray.size();
            importArray.parallelStream().forEach(item -> {
                JSONArray iValueArray = (JSONArray) item;

                //进度条
                i.getAndIncrement();
                double percent = (i.get() / size) * 100;
                int progress = (int) percent;
                stringRedisTemplate.opsForValue().set("WholeProduct" + user.getOrigin(), "" + progress, 2, TimeUnit.MINUTES);

                //跳过列名和导入规则行
                if (iValueArray.size() < 3 || "零件号".equals(iValueArray.getString(0))) return;
                String GuaranteePeriod = "";
                for (int n = 0; n < iValueArray.size(); n++) {
                    if (Objects.isNull(iValueArray.get(n))) continue;
                    switch (n) {
                        case 11: GuaranteePeriod = iValueArray.getString(11);
                            break;
                    }
                }

                //0、零件号 1、品牌 2、标准名称 3、车品牌 4、商品名称 5、商家编码 6、产品描述 7、库存数量 8、不含税单价 9、上架状态
                String[] strings = {iValueArray.getString(1), iValueArray.getString(2)};
                if (iValueArray.size() > 5 && UploadingProductUtil.isAllNotEmpty(iValueArray.getString(0), iValueArray.getString(1),
                        iValueArray.getString(4))&&("".equals(GuaranteePeriod)||"0".equals(GuaranteePeriod)||"1".equals(GuaranteePeriod)||
                        "3".equals(GuaranteePeriod)||"6".equals(GuaranteePeriod)||"12".equals(GuaranteePeriod)||"24".equals(GuaranteePeriod)) && this.formatCheck(strings, allName, categories) &&
                        PNAndBrand.add(iValueArray.getString(0) + iValueArray.getString(1) + user.getPerson().getId())) {
                    SpProduct spProduct = new SpProduct();
                    //判断是原厂件还是品牌件
                    if (Objects.nonNull(quality.get(iValueArray.getString(1))) && "原厂(4S店)件、非原厂(4S店)件、再制造件".contains(quality.get(iValueArray.getString(1)))) {
                        if (Objects.nonNull(iValueArray.getString(3)) && autoBrand.contains(iValueArray.getString(3))) {
                            //数据初始化与数据补全
                            spProduct.setName(iValueArray.getString(4));
                            spProduct.setSupplier(user.getPerson());
                            spProduct.setType("全车件");
                            spProduct.setSpBrand(spBrandRepository.findByName(iValueArray.getString(1)));
                            spProduct.setQuality(spProduct.getSpBrand().getQualityName());
                            spProduct.setOE(iValueArray.getString(0));
                            if(GuaranteePeriod.equals("")){
                                spProduct.setGuaranteePeriod("0");
                            }else{
                                spProduct.setGuaranteePeriod(GuaranteePeriod);
                            }
                            spProduct.setMerchantProduct(iValueArray.getString(5));
                            spProduct.setCategory(categoryRepository.findByName(iValueArray.getString(2)));
                            //非必填数据
                            maybe(iValueArray, spProduct);
                            //主数据数据补全
                            spProduct.setMateState("underway");
                            spProduct.setProductState("review");
                            spProduct.setStandardType("Whole");
                            spProduct.setAutomobile(automobileBrandRepository.findByautomobileBrand(iValueArray.getString(3)));
                            //保存
                            spProducts.add(spProductRepository.save(spProduct));
                        } else {
                            notProducts.add(UploadingProductUtil.wholeCause(iValueArray, allName, autoBrand, quality, categories,
                                    PNAndBrand, user.getPerson().getId()));
                        }

                    } else {
                        //数据初始化与数据补全
                        spProduct.setName(iValueArray.getString(4));
                        spProduct.setSupplier(user.getPerson());
                        spProduct.setType("全车件");
                        spProduct.setSpBrand(spBrandRepository.findByName(iValueArray.getString(1)));
                        spProduct.setQuality(spProduct.getSpBrand().getQualityName());
                        spProduct.setOE(iValueArray.getString(0));
                        if(GuaranteePeriod.equals("")){
                            spProduct.setGuaranteePeriod("0");
                        }else{
                            spProduct.setGuaranteePeriod(GuaranteePeriod);
                        }
                        if (Objects.nonNull(iValueArray.getString(3))) {
                            if(autoBrand.contains(iValueArray.getString(3))){
                                spProduct.setAutomobile(automobileBrandRepository.findByautomobileBrand(iValueArray.getString(3)));
                                spProduct.setMerchantProduct(iValueArray.getString(5));
                                spProduct.setCategory(categoryRepository.findByName(iValueArray.getString(2)));
                                //非必填数据
                                maybe(iValueArray, spProduct);
                                //主数据数据补全
                                spProduct.setMateState("underway");
                                spProduct.setProductState("review");
                                spProduct.setStandardType("brandWhole");
                                //保存
                                spProducts.add(spProductRepository.save(spProduct));
                            }else{
                                notProducts.add(UploadingProductUtil.wholeCause(iValueArray, allName, autoBrand, quality, categories,
                                        PNAndBrand, user.getPerson().getId()));
                            }

                        }else{
                            spProduct.setMerchantProduct(iValueArray.getString(5));
                            spProduct.setCategory(categoryRepository.findByName(iValueArray.getString(2)));
                            //非必填数据
                            maybe(iValueArray, spProduct);
                            //主数据数据补全
                            spProduct.setMateState("underway");
                            spProduct.setProductState("review");
                            spProduct.setStandardType("brandWhole");
                            //保存
                            spProducts.add(spProductRepository.save(spProduct));
                        }

                    }
                } else {
                    //不合格数据
                    notProducts.add(UploadingProductUtil.wholeCause(iValueArray, allName, autoBrand, quality, categories,
                            PNAndBrand, user.getPerson().getId()));
                }

            });
        });
        oilyProductRepository.flush();
        //用Redis，缓存进度条和结果
        stringRedisTemplate.opsForValue().set("not_WholeProducts" + user.getOrigin(), notProducts.toString(), 2, TimeUnit.HOURS);
        //进度条100%
        stringRedisTemplate.opsForValue().set("WholeProduct" + user.getOrigin(), "100", 2, TimeUnit.MINUTES);
        //用于结果页面展示
        stringRedisTemplate.opsForValue().set("successfulWhole" + user.getOrigin(), "" + spProducts.size(), 4, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set("failingWhole" + user.getOrigin(), "" + notProducts.size(), 4, TimeUnit.MINUTES);
        return spProducts;
    }


    /**
     * 非必填数据，防止下标越界
     *
     * @param iValueArray
     * @param spProduct
     */
    private void maybe(JSONArray iValueArray, SpProduct spProduct) {
        spProduct.setNotTaxUnitPrice(0.00);
        spProduct.setMerchantStockQty(0);
        spProduct.setPutawayState(false);
        switch (iValueArray.size()) {
            case 7: {
                spProduct.setDescribe(iValueArray.getString(6));
                break;
            }
            case 8: {
                spProduct.setMerchantStockQty(Objects.isNull(iValueArray.getString(7)) ? 0 :
                        Pattern.matches("[0-9]*", iValueArray.getString(7)) ? iValueArray.getInteger(7) : 0);
                spProduct.setDescribe(iValueArray.getString(6));
                break;
            }
            case 9: {
                spProduct.setNotTaxUnitPrice(Objects.isNull(iValueArray.getString(8)) ? 0 :
                        Pattern.matches("^\\d+(\\.\\d+)?$", iValueArray.getString(8)) ?
                                Double.parseDouble(String.format("%.2f", iValueArray.getDouble(8))) : 0);
                spProduct.setMerchantStockQty(Objects.isNull(iValueArray.getString(7)) ? 0 :
                        Pattern.matches("[0-9]*", iValueArray.getString(7)) ? iValueArray.getInteger(7) : 0);
                spProduct.setDescribe(iValueArray.getString(6));
                break;
            }
            case 10: {
                spProduct.setNotTaxUnitPrice(Objects.isNull(iValueArray.getString(8)) ? 0 :
                        Pattern.matches("^\\d+(\\.\\d+)?$", iValueArray.getString(8)) ?
                                Double.parseDouble(String.format("%.2f", iValueArray.getDouble(8))) : 0);
                spProduct.setMerchantStockQty(Objects.isNull(iValueArray.getString(7)) ? 0 :
                        Pattern.matches("[0-9]*", iValueArray.getString(7)) ? iValueArray.getInteger(7) : 0);
                spProduct.setPutawayState("上架".equals(iValueArray.getString(9)));
                spProduct.setDescribe(iValueArray.getString(6));
                break;
            }
            case 11: {
                spProduct.setPlaceOfOrigin(iValueArray.getString(10));
                spProduct.setNotTaxUnitPrice(Objects.isNull(iValueArray.getString(8)) ? 0 :
                        Pattern.matches("^\\d+(\\.\\d+)?$", iValueArray.getString(8)) ?
                                Double.parseDouble(String.format("%.2f", iValueArray.getDouble(8))) : 0);
                spProduct.setMerchantStockQty(Objects.isNull(iValueArray.getString(7)) ? 0 :
                        Pattern.matches("[0-9]*", iValueArray.getString(7)) ? iValueArray.getInteger(7) : 0);
                spProduct.setPutawayState("上架".equals(iValueArray.getString(9)));
                spProduct.setDescribe(iValueArray.getString(6));
                break;
            }
            case 12: {
                spProduct.setPlaceOfOrigin(iValueArray.getString(10));
                spProduct.setNotTaxUnitPrice(Objects.isNull(iValueArray.getString(8)) ? 0 :
                        Pattern.matches("^\\d+(\\.\\d+)?$", iValueArray.getString(8)) ?
                                Double.parseDouble(String.format("%.2f", iValueArray.getDouble(8))) : 0);
                spProduct.setMerchantStockQty(Objects.isNull(iValueArray.getString(7)) ? 0 :
                        Pattern.matches("[0-9]*", iValueArray.getString(7)) ? iValueArray.getInteger(7) : 0);
                spProduct.setPutawayState("上架".equals(iValueArray.getString(9)));
                spProduct.setDescribe(iValueArray.getString(6));
                break;
            }
        }
    }

    /**
     * 标准对照与字段回写
     *
     * @param outboxPayloadWrapper 传入匹配的商品
     */
    @OutboxSubscriber(id = "sp.spProduct.standardContrast", name = "通过事务发件箱实现标准对照/状态字段回写")
    public void standardContrast(OutboxPayloadWrapper outboxPayloadWrapper) {
        // 导入商品数据
        JSONArray importData = JSON.parseArray(outboxPayloadWrapper.getPayload());
        if (importData.size() <= 0) return;

        /* 组装品牌件匹配的 condition  */
        JSONArray brandPartsArray = getDataCenterProduct("dc.brandProduct.findAll");   // 数据中心标准数据(品牌件)
        //数据对比与状态回写（品牌件），将品牌+零件号做为map的key
        Map<String, JSONObject> brandPartsConditionMap = brandPartsArray.stream().filter(Objects::nonNull).collect(Collectors.toMap(item -> {
                    JSONObject spProduct = (JSONObject) item;
                    return spProduct.getString("brand") + spProduct.getString("brandMark");
                },
                item -> (JSONObject) item));

        //状态回写
        importData.stream().forEach(item -> {
            String id = ((JSONObject) item).getString("id");
            SpProduct spProduct = spProductRepository.findOne(id);
            //判断是车品牌是否为空 不为空则走全车件匹配
            if (spProduct.getAutomobile()!=null) {
                wholePartsContrast(spProduct);    // 全车件匹配
            } else {
                //品牌件
                brandPartsContrast(brandPartsConditionMap, spProduct);   // 品牌件匹配
            }

        });
    }

    /**
     * 根据传入的方法参数获取数据中心库中的标准商品
     * 分页查询
     *
     * @param method 传入调用的 ESB
     * @return JSONArray
     */
    private JSONArray getDataCenterProduct(String method) {
        JSONObject json = JSON.parseObject(super.invoke(method, MapUtil.mapper("page", 0, "size", 2000)));
        JSONArray body = json.getJSONObject("body").getJSONArray("content");
        for (int i = 1; i < json.getJSONObject("body").getInteger("pages"); i++) {
            json = JSON.parseObject(super.invoke(method, MapUtil.mapper("page", i, "size", 2000)));
            body.addAll(json.getJSONObject("body").getJSONArray("content"));
        }
        return body;
    }

    /**
     * 全车件
     *
     * @param spProduct    传入商品
     */
    private void wholePartsContrast(SpProduct spProduct) {
        JSONObject json = JSONObject.parseObject(invoke("dc.originalProduct.getEPC",MapUtil.mapper("automobile", spProduct.getAutomobile().getAutomobileBrand(),
                "oe", spProduct.getOE())));
        JSONArray standardId = json.getJSONArray("body");
        //原厂件
        if (!standardId.isEmpty()) {
            //匹配成功
            spProduct.setMateState("succeed");
            spProduct.setProductState(spProduct.isPutawayState() ? "offer" : "awaitPutaway");
            spProduct.setStandardId(standardId.getJSONObject(0).getString("PJMCID"));
            spProductRepository.saveAndFlush(spProduct);
        } else {
            //匹配失败
            spProduct.setMateState("fail");
            spProduct.setProductState("notOffer");
            spProductRepository.saveAndFlush(spProduct);
        }
    }

    /**
     * 品牌件匹配
     *
     * @param conditionMap 条件
     * @param spProduct    传入商品
     */
    private void brandPartsContrast(Map<String, JSONObject> conditionMap, SpProduct spProduct) {
        JSONObject normalData = conditionMap.get(spProduct.getSpBrand().getName() + spProduct.getOE());
        if (Objects.nonNull(normalData)) {
            //匹配成功
            spProduct.setMateState("succeed");
            spProduct.setProductState(spProduct.isPutawayState() ? "offer" : "awaitPutaway");
            spProduct.setStandardId(normalData.getString("id"));
            spProductRepository.saveAndFlush(spProduct);
        } else {
            //匹配失败
            spProduct.setMateState("fail");
            spProduct.setProductState("notOffer");
            spProductRepository.saveAndFlush(spProduct);
        }
    }


    /**
     * 校验数据是否合法
     *
     * @param strings
     * @return
     */
    public boolean formatCheck(String[] strings, List<String> allName, List<String> categories) {
        if (strings.length == 0) {
            return false;
        }
        for (String item : strings) {
            if (Objects.isNull(item)) continue;
            if (allName.contains(item) || categories.contains(item)) {
                continue;
            }
            return false;
        }
        return true;
    }

    /**
     * 进度条
     *
     * @return
     */
    public String progress(SimpleRequest request) {
        User user = userRepository.findOne(Integer.parseInt(request.getSession().getUserId()));
        //批量更新商品价格库存进度条
        if ("stock".equals(request.get("type"))) {
            String product_stock = stringRedisTemplate.opsForValue().get("product_stock" + user.getOrigin());
            if ("100".equals(product_stock)) stringRedisTemplate.delete("product_stock" + user.getOrigin());
            return product_stock;
        }
        String wholeProduct = stringRedisTemplate.opsForValue().get("WholeProduct" + user.getOrigin());
        if ("100".equals(wholeProduct)) stringRedisTemplate.delete("WholeProduct" + user.getOrigin());
        return wholeProduct;
    }

    /**
     * 上传结果
     *
     * @param request
     * @return
     */
    public String resultPage(SimpleRequest request) {
        User user = userRepository.findOne(Integer.parseInt(request.getSession().getUserId()));
        if ("stock".equals(request.get("type")))
            return "本次成功导入" + stringRedisTemplate.opsForValue().get("successful_product_stock" + user.getOrigin()) + "条\n" +
                    "导入失败" + stringRedisTemplate.opsForValue().get("failing_product_stock" + user.getOrigin()) + "条";
        return "本次成功导入" + stringRedisTemplate.opsForValue().get("successfulWhole" + user.getOrigin()) + "条\n" + "导入失败" + stringRedisTemplate.opsForValue().get("failingWhole" + user.getOrigin()) + "条";
    }

    /**
     * 下载失败结果
     *
     * @param request
     * @return
     */
    public Map productDetail(SimpleRequest request) {
        User user = userRepository.findOne(Integer.parseInt(request.getSession().getUserId()));
        String productStocks = stringRedisTemplate.opsForValue().get("not_WholeProducts" + user.getOrigin());
        JSONArray objects = JSONArray.parseArray(productStocks);
        assert objects != null;
        stringRedisTemplate.delete("not_WholeProducts" + user.getOrigin());
        return MapUtil.mapper("content", new ArrayList<>(objects), "total", objects.size(), "pages", request.get("page"));
    }

    /**
     * 批量更新价格库存
     *
     * @param request
     */
    public void uploadingSpProductStock(SimpleRequest request) {
        //Excel信息
        JSONObject importData = request.get("importData");
        User user = userRepository.findOne(Integer.parseInt(request.getSession().getUserId()));

        //准入校验与数据补全
        List spProducts = appendImportReturn(importData, user);
        JSONObject returnData = new JSONObject();
    }

    /**
     * 准入校验与数据补全
     *
     * @param importData
     * @param user
     * @return
     */
    private List appendImportReturn(JSONObject importData, User user) {
        List spProducts = Collections.synchronizedList(new ArrayList());
        List notProducts = Collections.synchronizedList(new ArrayList());
        Set<String> PNAndBrand = new HashSet<>();
        //开始校验数据
        importData.forEach((k, v) -> {
            JSONArray importArray = (JSONArray) v;
            AtomicInteger i = new AtomicInteger(1);
            double size = importArray.size();
            importArray.stream().forEach(item -> {
                JSONArray iValueArray = (JSONArray) item;

                //进度条
                i.getAndIncrement();
                double percent = (i.get() / size) * 100;
                int progress = (int) percent;
                stringRedisTemplate.opsForValue().set("product_stock" + user.getOrigin(), "" + progress, 2, TimeUnit.MINUTES);
                //跳过列名和导入规则行
                if ("零件号".equals(iValueArray.getString(0)) ||
                        "‘零件号’必填；".equals(iValueArray.getString(0))) return;
                SpProduct spProduct = spProductRepository.findByPNAndSpBrand(iValueArray.getString(0), spBrandRepository.findByName(iValueArray.getString(1)), user.getPerson(),iValueArray.getString(2));
                //0、零件号 1、品牌 2、商品名称  3、库存数量 4、不含税单价
                if (iValueArray.size() == 5 && UploadingProductUtil.isAllNotEmpty(iValueArray.getString(0), iValueArray.getString(1), iValueArray.getString(2),
                        iValueArray.getString(3), iValueArray.getString(4), spProduct) && PNAndBrand.add(iValueArray.getString(0) + iValueArray.getString(1)+ iValueArray.getString(3))) {

                    //更新商品价格库存
                    spProduct.setNotTaxUnitPrice(Pattern.matches("^\\d+(\\.\\d+)?$", iValueArray.getString(4)) ? iValueArray.getDouble(4) : 0L);
                    spProduct.setMerchantStockQty(Pattern.matches("[0-9]*", iValueArray.getString(3)) ? iValueArray.getInteger(3) : 0);

                    //保存
                    spProducts.add(spProductRepository.save(spProduct));
                } else {
                    notProducts.add(UploadingProductUtil.StockCause(iValueArray, spProduct));
                }

            });
        });

        //用Redis，缓存进度条和结果
        stringRedisTemplate.opsForValue().set("not_stocks" + user.getOrigin(), notProducts.toString(), 5, TimeUnit.MINUTES);
        //进度条
        stringRedisTemplate.opsForValue().set("product_stock" + user.getOrigin(), "100", 2, TimeUnit.MINUTES);
        //用于结果页面展示
        stringRedisTemplate.opsForValue().set("successful_product_stock" + user.getOrigin(), "" + spProducts.size(), 4, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set("failing_product_stock" + user.getOrigin(), "" + notProducts.size(), 4, TimeUnit.MINUTES);
        spProductRepository.flush();
        return spProducts;
    }

    /**
     * 批量更新商品库存价格下载失败结果
     *
     * @param request
     * @return
     */
    public Map detail(SimpleRequest request) {
        User user = userRepository.findOne(Integer.parseInt(request.getSession().getUserId()));
        String productStocks = stringRedisTemplate.opsForValue().get("not_stocks" + user.getOrigin());
        JSONArray objects = JSONArray.parseArray(productStocks);
        assert objects != null;
        stringRedisTemplate.delete("not_stocks" + user.getOrigin());
        return MapUtil.mapper("content", new ArrayList<>(objects), "total", objects.size(), "pages", request.get("page"));
    }


    /**
     * 下载
     *
     * @param request
     * @return
     */
    public Map download(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONObject condition = jo.getJSONObject("condition");
        String PN = condition.getString("pn");
        String merchantProduct = condition.getString("merchantProduct");
        String name = condition.getString("name");
        if ("".equals(PN)) PN = null;
        if ("".equals(name)) name = null;
        if ("".equals(merchantProduct)) merchantProduct = null;
        String productState = condition.getString("productState");
        if ("审核中".equals(productState)) productState = "review";
        if ("无法系统报价".equals(productState)) productState = "notOffer";
        if ("待维护品牌件关系".equals(productState)) productState = "awaitMaintain";
        if ("可系统报价".equals(productState)) productState = "offer";
        if ("待上架".equals(productState)) productState = "awaitPutaway";
        if ("临时商品".equals(productState)) productState = "history";
        User user = userRepository.findOne(Integer.valueOf(request.getSession().getUserId()));
        PartyRole supplier = partyRoleRepository.findOne(user.getPerson().getId());
        if ("yyadmin".equals(user.getOrigin())) {
            supplier = null;
        }
        Page<SpProduct> page = spProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("merchantProduct", "EQ", merchantProduct,
                "OE", "EQ", PN,
                "spBrand", "EQ", condition.getObject("brand", SpBrand.class),
                "productState", "EQ", productState,
                "name", "EQ", name,
                "type", "EQ", condition.getString("type"),
                "supplier", "EQ", supplier,
                "category", "EQ", condition.getObject("category", Category.class)
                ),
                PageRequest.of(request.get("page"), request.get("size"), Sort.by(Sort.Direction.DESC, "id")));
        page.getContent().forEach(item -> item.setDis(item.getProductState()));
        return MapUtil.mapper("content", page.getContent(), "total", page.getTotalElements(), "pages", page.getTotalPages(), "page", request.get("page"));
    }

    /**
     * 下载品牌清单
     *
     * @param request
     * @return
     */
    public Map brandList(SimpleRequest request) {
        if ("品牌清单".equals(request.get("queryname"))) {
            List<Map<String, String>> allName = spBrandRepository.findAllBrand();
            return MapUtil.mapper("content", allName, "total", allName.size(), "pages", request.get("page"));
        }
        if ("标准名称清单".equals(request.get("queryname"))) {
            List<Map<String, String>> maps = categoryRepository.nameList();
            return MapUtil.mapper("content", maps, "total", maps.size(), "pages", request.get("page"));
        }

        List<Map<String, String>> autoMaps = automobileBrandRepository.nameList();
        return MapUtil.mapper("content", autoMaps, "total", autoMaps.size(), "pages", request.get("page"));
    }

    public SpProduct enquiryItem(SimpleRequest request){

        return spProductRepository.findBySupplierAndState(request.getJO().getString("spId"));

    }


    /**
     *要货补货管理 需根据车架号+门店+供应商平台商品查询对应的报价单的报价结果
     * @param request
     * @return
     */
    public List<Map> enquiryVin(SimpleRequest request){
        String vin = request.getJO().getString("vin");//车架号
        String id = request.getJO().getString("id");//门店
        String offerId = request.getJO().getString("offerId");
        int index = offerId.indexOf("/");
        String quoteResultId = offerId.substring(0, index);//报价结果ID
        List<Map> mapList = new ArrayList<>();
        //通过车架号+门店得到询价单号
        List<Enquiry> enquiries = enquiryRepository.findByServicePlanId(id,vin);
        if(enquiries.size()==0)return mapList;
        for (Enquiry e:enquiries) {
            //通过询价单号+商品ID 匹配商品
            List<QuoteResult> quoteResults = quoteResultRepository.findByEnquiryIdByProduct(e.getId(),quoteResultId);
            if(quoteResults.size()==0)continue;
            for (QuoteResult quoteResult:quoteResults) {
                Map map = new HashMap();
                map.put("spProduct",quoteResult.getProduct());
                map.put("enquiryId",quoteResult.getEnquiryId());
                map.put("uniqueValue", quoteResult.getId()+quoteResult.getProduct().getId());//唯一值
                map.put("SUPPLIER_ID", quoteResult.getSupplierId());
                map.put("P001", quoteResult.getNotTaxUnitPrice());
                map.put("priceNo", quoteResult.getPriceNo());
                map.put("quoteId", quoteResult.getQuoteId());
                mapList.add(map);
            }
        }
        return mapList;
    }


    public String anewMatching(SimpleRequest request){
        List<OutboxEvent> events  = SpringManager.getBean(OutboxEventRepository.class).findAll(" SELECT id FROM OUTBOX_EVENT WHERE AGGREGATE_ID LIKE 'ERPCXPPSJ%' ");
        if(events.size()>0) return "数据匹配中请稍后重试！";
        Integer num = spProductRepository.findCountByMateState();
        if(num>=50000)return "匹配数量超标，匹配失败！";

        List<SpProduct> spProducts = spProductRepository.findByMasteState();
        Map<String ,List<SpProduct>> map = spProducts.stream().collect(Collectors.groupingBy(SpProduct ::getType));
        map.forEach((k,v) ->{
            //规则匹配
            OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
            switch (k) {
                case "全车件":
                    wrapper.setSubscriber("sp.spProduct.standardContrast");
                    break;
                case "轮胎":
                    wrapper.setSubscriber("sp.tyreProduct.standardContrast");
                    break;
                case "机油":
                    wrapper.setSubscriber("sp.oilyProduct.standardContrast");
                    break;
                case "蓄电池":
                    wrapper.setSubscriber("sp.accumulatorProduct.standardContrast");
                    break;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yy-mm-dd HH:mm:ss");
            String random = String.valueOf(Math.random()).substring(0, 3);
            if(v.size()>1000){
                List<SpProduct> spProductList = new ArrayList<>();
                for(int i=0;i<v.size();i++){
                    spProductList.add(v.get(i));
                    if(spProductList.size()==1000 || i==v.size()-1){
                        wrapper.setAggregateId("ERPCXPPSJ" + sdf.format(new Date()) + random);//聚合根ID（非必项）tp:方便追溯发生异常的服务,最好是业务单据单号
                        wrapper.setPayload(JSON.toJSONString(spProductList));
                        wrapper.setSubscriber("商品匹配");
                        SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);
                        spProductList = new ArrayList<>();
                    }

                }
            }else{
                wrapper.setAggregateId("ERPCXPPSJ" + sdf.format(new Date()) + random);//聚合根ID（非必项）tp:方便追溯发生异常的服务,最好是业务单据单号
                wrapper.setPayload(JSON.toJSONString(v));
                wrapper.setSubscriber("商品匹配");
                SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);
            }
        });
        return "匹配中";

    }

    /**
     * 根据报价明细查找商品
     * @param request
     * @return
     */
    public SpProduct findByQuoteResult (SimpleRequest request) {
          JSONObject requestJO = request.getJO();
          QuoteResult quoteResult = quoteResultRepository.findOne(requestJO.getString("id"));
          SpProduct spProduct = spProductRepository.findOne(quoteResult.getProduct().getId());
        return spProduct;
    }

    /**
     * 获取商品价格
     * @return 商品价格
     */
    public Double findProductPrice(SimpleRequest request){
        String name = request.get("name");
        User user = request.getCurrentUser();
        SpProduct spProduct = spProductRepository.findByNameAndSupplier(name, user.getPerson().getId());
        if (Objects.isNull(spProduct)) return 0.0;
        return spProduct.getNotTaxUnitPrice();
    }


}
